package item1;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ClassManagementSystemGUI extends JFrame {
    //存储班级信息的列表
    private List<String> classes;
    //存储小组信息的列表
    private List<Group> groups;
    //存储学生信息的列表
    private List<Student> students;
    //用于显示信息的文本区域
    private JTextArea displayArea;
    //用于生成随机数的对象
    private Random random;

    //构造函数
    public ClassManagementSystemGUI() {
        // 初始化数据(数据结构（classes、groups、students）和随机数生成器)
        classes = new ArrayList<>();
        groups = new ArrayList<>();
        students = new ArrayList<>();
        random = new Random();

        // 设置窗口
        //窗口标题
        setTitle("班级管理系统");
        //大小
        setSize(800, 600);
        //关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //居中显示
        setLocationRelativeTo(null);

        // 创建主面板，设置布局和边距
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建显示区域
        //添加不可编辑的文本区域到滚动面板中，并将其添加到主面板中心。
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        displayArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        JScrollPane scrollPane = new JScrollPane(displayArea);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建功能按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(4, 1, 5, 5));

        //添加四个子面板（班级管理、小组管理、学生管理和随机点名），每个子面板都包含相应的按钮
        // 班级管理面板
        JPanel classPanel = createSectionPanel("班级管理",
                new String[]{"新增班级", "维护班级", "班级列表"});

        // 小组管理面板
        JPanel groupPanel = createSectionPanel("小组管理",
                new String[]{"新增小组", "维护小组", "小组列表"});

        // 学生管理面板
        JPanel studentPanel = createSectionPanel("学生管理",
                new String[]{"新增学生", "维护学生", "学生列表"});

        // 随机点名面板
        JPanel randomPanel = createSectionPanel("随机点名",
                new String[]{"随机选组", "随机选人", "记录管理"});

        buttonPanel.add(classPanel);
        buttonPanel.add(groupPanel);
        buttonPanel.add(studentPanel);
        buttonPanel.add(randomPanel);

        //将功能按钮面板添加到主面板的东侧（右侧）
        mainPanel.add(buttonPanel, BorderLayout.EAST);
        add(mainPanel);
    }

    //辅助方法
    private JPanel createSectionPanel(String title, String[] buttonNames) {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setBorder(BorderFactory.createTitledBorder(title));

        for (String name : buttonNames) {
            JButton button = new JButton(name);
            button.addActionListener(e -> handleButtonClick(name));
            panel.add(button);
        }

        return panel;
    }

    private void handleButtonClick(String command) {
        switch (command) {
            case "新增班级": showAddClassDialog(); break;
            case "维护班级": showUpdateClassDialog(); break;
            case "班级列表": listClasses(); break;
            case "新增小组": showAddGroupDialog(); break;
            case "维护小组": showUpdateGroupDialog(); break;
            case "小组列表": listGroups(); break;
            case "新增学生": showAddStudentDialog(); break;
            case "维护学生": showUpdateStudentDialog(); break;
            case "学生列表": listStudents(); break;
            case "随机选组": randomSelectGroup(); break;
            case "随机选人": randomSelectStudent(); break;
            case "记录管理": showRecordDialog(); break;
        }
    }

    // 班级管理方法
    private void showAddClassDialog() {
        String className = JOptionPane.showInputDialog(this, "请输入班级名称：");
        if (className != null && !className.trim().isEmpty()) {
            classes.add(className);
            displayArea.append("新增班级：" + className + "\n");
        }
    }

    private void showUpdateClassDialog() {
        if (classes.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无班级可维护！");
            return;
        }

        String selectedClass = (String) JOptionPane.showInputDialog(this,
                "选择要维护的班级：", "维护班级",
                JOptionPane.QUESTION_MESSAGE, null,
                classes.toArray(), classes.get(0));

        if (selectedClass != null) {
            String newName = JOptionPane.showInputDialog(this,
                    "请输入新的班级名称：", selectedClass);
            if (newName != null && !newName.trim().isEmpty()) {
                int index = classes.indexOf(selectedClass);
                classes.set(index, newName);
                displayArea.append("更新班级：" + selectedClass + " -> " + newName + "\n");
            }
        }
    }

    private void listClasses() {
        displayArea.append("班级列表：\n");
        for (String className : classes) {
            displayArea.append(className + "\n");
        }
        displayArea.append("-------------------\n");
    }

    // 小组管理方法
    private void showAddGroupDialog() {
        if (students.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请先添加学生！");
            return;
        }

        JTextField groupNameField = new JTextField();
        JList<Student> studentList = new JList<>(students.toArray(new Student[0]));
        studentList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        JScrollPane listScrollPane = new JScrollPane(studentList);
        listScrollPane.setPreferredSize(new Dimension(200, 150));

        Object[] message = {
                "小组名称:", groupNameField,
                "选择学生:", listScrollPane
        };

        int option = JOptionPane.showConfirmDialog(this, message, "新增小组",
                JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION) {
            String groupName = groupNameField.getText().trim();
            if (!groupName.isEmpty()) {
                List<Student> selectedStudents = studentList.getSelectedValuesList();
                if (!selectedStudents.isEmpty()) {
                    Group newGroup = new Group(groupName,
                            selectedStudents.toArray(new Student[0]));
                    groups.add(newGroup);
                    displayArea.append("新增小组：" + newGroup + "\n");
                } else {
                    JOptionPane.showMessageDialog(this, "请至少选择一名学生！");
                }
            } else {
                JOptionPane.showMessageDialog(this, "小组名称不能为空！");
            }
        }
    }

    private void showUpdateGroupDialog() {
        if (groups.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无小组可维护！");
            return;
        }

        Group selectedGroup = (Group) JOptionPane.showInputDialog(this,
                "选择要维护的小组：", "维护小组",
                JOptionPane.QUESTION_MESSAGE, null,
                groups.toArray(), groups.get(0));

        if (selectedGroup != null) {
            JTextField nameField = new JTextField(selectedGroup.getGroupName());
            JList<Student> studentList = new JList<>(students.toArray(new Student[0]));
            studentList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

            // 预选当前组内的学生
            Student[] currentStudents = selectedGroup.getStudents();
            int[] selectedIndices = new int[currentStudents.length];
            for (int i = 0; i < currentStudents.length; i++) {
                for (int j = 0; j < students.size(); j++) {
                    if (currentStudents[i].getName().equals(students.get(j).getName())) {
                        selectedIndices[i] = j;
                    }
                }
            }
            studentList.setSelectedIndices(selectedIndices);

            JScrollPane listScrollPane = new JScrollPane(studentList);
            listScrollPane.setPreferredSize(new Dimension(200, 150));

            Object[] message = {
                    "小组名称:", nameField,
                    "选择学生:", listScrollPane
            };

            int option = JOptionPane.showConfirmDialog(this, message, "更新小组",
                    JOptionPane.OK_CANCEL_OPTION);

            if (option == JOptionPane.OK_OPTION) {
                String newName = nameField.getText().trim();
                if (!newName.isEmpty()) {
                    List<Student> selectedStudents = studentList.getSelectedValuesList();
                    if (!selectedStudents.isEmpty()) {
                        int index = groups.indexOf(selectedGroup);
                        groups.set(index, new Group(newName,
                                selectedStudents.toArray(new Student[0])));
                        displayArea.append("更新小组：" + selectedGroup.getGroupName() +
                                " -> " + newName + "\n");
                    } else {
                        JOptionPane.showMessageDialog(this, "请至少选择一名学生！");
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "小组名称不能为空！");
                }
            }
        }
    }

    private void listGroups() {
        displayArea.append("小组列表：\n");
        for (Group group : groups) {
            displayArea.append(group.toString() + "\n");
        }
        displayArea.append("-------------------\n");
    }

    // 学生管理方法
    private void showAddStudentDialog() {
        JTextField nameField = new JTextField();
        JTextField ageField = new JTextField();

        Object[] message = {
                "学生姓名:", nameField,
                "学生年龄:", ageField
        };

        int option = JOptionPane.showConfirmDialog(this, message, "新增学生",
                JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION) {
            String name = nameField.getText().trim();
            String ageStr = ageField.getText().trim();

            if (name.isEmpty()) {
                JOptionPane.showMessageDialog(this, "学生姓名不能为空！");
                return;
            }

            try {
                int age = Integer.parseInt(ageStr);
                Student newStudent = new Student(name, age);
                students.add(newStudent);
                displayArea.append("新增学生：" + newStudent + "\n");
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "请输入有效的年龄！");
            }
        }
    }

    private void showUpdateStudentDialog() {
        if (students.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无学生可维护！");
            return;
        }

        Student selectedStudent = (Student) JOptionPane.showInputDialog(this,
                "选择要维护的学生：", "维护学生",
                JOptionPane.QUESTION_MESSAGE, null,
                students.toArray(), students.get(0));

        if (selectedStudent != null) {
            JTextField nameField = new JTextField(selectedStudent.getName());
            JTextField ageField = new JTextField(String.valueOf(selectedStudent.getAge()));

            Object[] message = {
                    "学生姓名:", nameField,
                    "学生年龄:", ageField
            };

            int option = JOptionPane.showConfirmDialog(this, message, "更新学生",
                    JOptionPane.OK_CANCEL_OPTION);

            if (option == JOptionPane.OK_OPTION) {
                String newName = nameField.getText().trim();
                String ageStr = ageField.getText().trim();

                if (newName.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "学生姓名不能为空！");
                    return;
                }

                try {
                    int newAge = Integer.parseInt(ageStr);
                    int index = students.indexOf(selectedStudent);
                    students.set(index, new Student(newName, newAge));
                    displayArea.append("更新学生：" + selectedStudent + " -> " +
                            students.get(index) + "\n");
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "请输入有效的年龄！");
                }
            }
        }
    }

    private void listStudents() {
        displayArea.append("学生列表：\n");
        for (Student student : students) {
            displayArea.append(student.toString() + "\n");
        }
        displayArea.append("-------------------\n");
    }
    // 随机点名方法
    private void randomSelectGroup() {
        if (groups.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无小组可选择！");
            return;
        }
        Group selectedGroup = Main.getRandomGroup(groups.toArray(new Group[0]));
        displayArea.append("随机选中小组：" + selectedGroup + "\n");
        displayArea.append("-------------------\n");
    }

    private void randomSelectStudent() {
        String[] options = {"从班级随机选择", "从小组随机选择"};
        int choice = JOptionPane.showOptionDialog(this,
                "请选择随机选择方式", "随机选择学生",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, options, options[0]);

        if (choice == 0) {
            randomSelectFromClass();
        } else if (choice == 1) {
            randomSelectFromGroup();
        }
    }

    private void randomSelectFromClass() {
        if (students.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无学生可选择！");
            return;
        }
        Student selectedStudent = Main.getRandomStudent(students.toArray(new Student[0]));
        displayArea.append("从班级随机选中学生：" + selectedStudent + "\n");
        displayArea.append("-------------------\n");
    }

    private void randomSelectFromGroup() {
        if (groups.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无小组可选择！");
            return;
        }

        Group selectedGroup = (Group) JOptionPane.showInputDialog(this,
                "选择小组：", "从小组随机选择",
                JOptionPane.QUESTION_MESSAGE, null,
                groups.toArray(), groups.get(0));

        if (selectedGroup != null) {
            Student[] groupStudents = selectedGroup.getStudents();
            if (groupStudents.length == 0) {
                JOptionPane.showMessageDialog(this, "该小组暂无学生！");
                return;
            }
            Student selectedStudent = Main.getRandomStudent(groupStudents);
            displayArea.append("从小组 " + selectedGroup.getGroupName() +
                    " 随机选中学生：" + selectedStudent + "\n");
            displayArea.append("-------------------\n");
        }
    }

    // 记录管理方法
    private void showRecordDialog() {
        String[] options = {"小组评分", "考勤记录", "答题记录"};
        int choice = JOptionPane.showOptionDialog(this,
                "请选择记录类型", "记录管理",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, options, options[0]);

        switch (choice) {
            case 0: showGroupScoreDialog(); break;
            case 1: showAttendanceDialog(); break;
            case 2: showAnswerRecordDialog(); break;
        }
    }

    private void showGroupScoreDialog() {
        if (groups.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无小组可评分！");
            return;
        }

        Group selectedGroup = (Group) JOptionPane.showInputDialog(this,
                "选择要评分的小组：", "小组评分",
                JOptionPane.QUESTION_MESSAGE, null,
                groups.toArray(), groups.get(0));

        if (selectedGroup != null) {
            String scoreStr = JOptionPane.showInputDialog(this,
                    "请输入" + selectedGroup.getGroupName() + "的分数（0-100）：");
            try {
                int score = Integer.parseInt(scoreStr);
                if (score >= 0 && score <= 100) {
                    displayArea.append("小组 " + selectedGroup.getGroupName() +
                            " 评分：" + score + "\n");
                    displayArea.append("-------------------\n");
                } else {
                    JOptionPane.showMessageDialog(this, "分数必须在0-100之间！");
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "请输入有效的分数！");
            }
        }
    }

    private void showAttendanceDialog() {
        if (students.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无学生可记录考勤！");
            return;
        }

        Student selectedStudent = (Student) JOptionPane.showInputDialog(this,
                "选择要记录考勤的学生：", "考勤记录",
                JOptionPane.QUESTION_MESSAGE, null,
                students.toArray(), students.get(0));

        if (selectedStudent != null) {
            int option = JOptionPane.showConfirmDialog(this,
                    "学生 " + selectedStudent.getName() + " 是否出勤？",
                    "考勤记录",
                    JOptionPane.YES_NO_OPTION);

            String status = option == JOptionPane.YES_OPTION ? "出勤" : "缺勤";
            displayArea.append("学生 " + selectedStudent.getName() +
                    " 考勤记录：" + status + "\n");
            displayArea.append("-------------------\n");
        }
    }

    private void showAnswerRecordDialog() {
        if (students.isEmpty()) {
            JOptionPane.showMessageDialog(this, "暂无学生可记录答题！");
            return;
        }

        Student selectedStudent = (Student) JOptionPane.showInputDialog(this,
                "选择要记录答题的学生：", "答题记录",
                JOptionPane.QUESTION_MESSAGE, null,
                students.toArray(), students.get(0));

        if (selectedStudent != null) {
            JTextField questionField = new JTextField();
            JTextField answerField = new JTextField();

            Object[] message = {
                    "问题:", questionField,
                    "答案:", answerField
            };

            int option = JOptionPane.showConfirmDialog(this, message, "答题记录",
                    JOptionPane.OK_CANCEL_OPTION);

            if (option == JOptionPane.OK_OPTION) {
                String question = questionField.getText().trim();
                String answer = answerField.getText().trim();

                if (!question.isEmpty() && !answer.isEmpty()) {
                    int correctOption = JOptionPane.showConfirmDialog(this,
                            "答案是否正确？", "答题记录", JOptionPane.YES_NO_OPTION);
                    String result = correctOption == JOptionPane.YES_OPTION ? "正确" : "错误";

                    displayArea.append("学生 " + selectedStudent.getName() + " 答题记录：\n");
                    displayArea.append("问题：" + question + "\n");
                    displayArea.append("答案：" + answer + "\n");
                    displayArea.append("结果：" + result + "\n");
                    displayArea.append("-------------------\n");
                } else {
                    JOptionPane.showMessageDialog(this, "问题和答案不能为空！");
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> {
            ClassManagementSystemGUI gui = new ClassManagementSystemGUI();
            gui.setVisible(true);
        });
    }
}